<?php
    class Admincp_IndexController extends Main_Controller_Action
    {
    	private $_arrParam;
    	
        public function init()
        {
            $this->loadTemplates('admin');
            $this->_arrParam = $this->_request->getParams();
        }
        
        public function preDispatch()
        {
        	$auth = Zend_Auth::getInstance();
        	if(!$auth->hasIdentity()) {
        		if(($this->_request->getActionName() != 'login')
        		        &&($this->_request->getActionName() != 'forgotpassword')
        		        &&($this->_request->getActionName() != 'successforgot')
        		        &&($this->_request->getActionName() != 'success')
        		        &&($this->_request->getActionName() != 'resetpassword')) {
        		    $this->_redirect('admincp/index/login');
        		}
        	}
        }
        
        public function indexAction()
        {
            $this->_redirect('admincp/product');
        }
        
        public function loginAction()
        {
            $request = new Zend_Controller_Request_Http();
            $usernameCookie = $request->getCookie('userLogin');
            $passwordCookie = $request->getCookie('passLogin');
            $db = Zend_Registry::get('db');
            
            if(!empty($usernameCookie)) {
            	$auth = Zend_Auth::getInstance();
            	$authAdapter = new Zend_Auth_Adapter_DbTable($db);
            	$authAdapter->setTableName('user')
            				->setIdentityColumn('username')
            				->setCredentialColumn('password');
            	
            	$authAdapter->setIdentity($usernameCookie);
            	$authAdapter->setCredential($passwordCookie);
            	$select = $authAdapter->getDbSelect();
            	$select->where('status = 1');
            	
            	$result = $auth->authenticate($authAdapter);
            	$flag = false;
            	if($result->isValid()) {
            		$data = $authAdapter->getResultRowObject();
            		$auth->getStorage()->write($data);
            		$flag = true;
            	}
            	if($flag == true)
            		$this->_redirect('admincp/product');
            	else
            		$this->_redirect('admincp/index/login');
            }
            else {
            	$this->view->headTitle('Đăng nhập hệ thống');
            	$this->_helper->layout->setLayout('login');
            	
            	if($this->_request->isPost()) {
            		$auth = Zend_Auth::getInstance();
            		$authAdapter = new Zend_Auth_Adapter_DbTable($db);
            		$authAdapter->setTableName('user')
            					->setIdentityColumn('username')
            					->setCredentialColumn('password');
            		$count = 0;
            		
            		if(!Zend_Validate::is($this->_arrParam['username'], 'NotEmpty')) {
            			$this->view->error = 'Bạn chưa nhập đủ thông tin';
            			$count++;
            		}
            		else {
            			$this->view->usernameValue = $this->_arrParam['username'];
            		}
            		if(!Zend_Validate::is($this->_arrParam['password'], 'NotEmpty')) {
            			$this->view->error = 'Bạn chưa nhập đủ thông tin';
            			$count++;
            		}
            		
            		if($count == 0) {
            			$authAdapter->setIdentity($this->_arrParam['username']);
            			$authAdapter->setCredential(md5('tivi'.$this->_arrParam['password']));
            			
            			$select = $authAdapter->getDbSelect();
            			$select->where('status = 1');
            			
            			$result = $auth->authenticate($authAdapter);
            			$flag = false;
            			if($result->isValid()) {
            				$data = $authAdapter->getResultRowObject();
            				$auth->getStorage()->write($data);
            				if($this->_arrParam['rememberMe'] == 1) {
            					$expires = time() + 60 * 60 * 24 * 365;
            					setcookie('userLogin', $data->username, $expires);
            					setcookie('passLogin', $data->password, $expires);
            				}
            				$flag = true;
            			}
            			if($flag == true)
		            		$this->_redirect('admincp/product');
		            	else
		            		$this->view->error = 'Sai tên đăng nhập hoặc mật khẩu!';
            		}
            	}
            }
        }
        
        public function logoutAction()
        {
        	$auth = Zend_Auth::getInstance();
        	$auth->clearIdentity();
        	setcookie('userLogin', null, -1);
        	setcookie('passLogin', null, -1);
        	$this->_redirect('admincp/index/login');
        }
        
        public function forgotpasswordAction()
        {
            $this->_helper->layout->setLayout('forgotpassword');
            $captcha = new Zend_Captcha_Image();
            $captcha->setTimeout('300')
                    ->setWordlen('4')
                    ->setHeight('64')
                    ->setWidth('90')
                    ->setDotNoiseLevel('0')
                    ->setLineNoiseLevel('0')
                    ->setImgDir(APPLICATION_PATH.'/../public/captcha/images/')
                    ->setImgUrl('/furniture/public/captcha/images')
                    ->setFont('public/captcha/fonts/ARIAL.TTF')
                    ->setFontSize('18');
            $captcha->generate();
            $this->view->captcha = $captcha->render($this->view);
            $this->view->captchaID = $captcha->getId();
            $captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_'.$captcha->getId());
            $captchaSession->word = $captcha->getWord();
            
            if($this->_request->isPost()) {
                $strTrim = new Zend_Filter_StringTrim();
                $captchaID = $this->_arrParam['captcha_id'];
                $captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_'.$captchaID);
                $captchaIterator = $captchaSession->getIterator();
                $captchaWord = $captchaIterator['word'];
                $username = $strTrim->filter(strtolower(strip_tags($this->_arrParam['username'])));
                $captcha = $this->_arrParam['captcha'];
                $flag = true;
                
                $validate = new Admincp_Form_ValidateUser();
                $model = new Admincp_Model_User();
                if(($validate->validUsername($username) == true) && ($model->checkUser(null, $username) > 0)) {
                    $this->view->usernameValue = $username;
                }
                else {
                    $this->view->error = 'Sai tên đăng nhập';
                    $flag = false;
                }
                if($captcha != $captchaWord) {
                    $this->view->error = 'Mã xác nhận không chính xác';
                    $flag = false;
                }
                
                if($flag == true) {
                    $tr = new Zend_Mail_Transport_Smtp('smtp.zoho.com', array(
                        'auth' => 'login',
                        'username' => 'thongbao.baotoan@gmail.com',
                        'password' => '123456aA@',
                        'ssl' => 'ssl',
                        'port' => 465)
                    );
                    Zend_Mail::setDefaultTransport($tr);
                    $code = time().mt_rand(5, 99999999);
                    $value = $model->getUserByUsername($username);
                    $data = array(
                        'code'=>$code,
                    );
                    $model->updateUser($data, $value['id']);
                    $mask = APPLICATION_PATH."/../public/captcha/images/*.png";
                    array_map("unlink",glob($mask));
                    $message = 'Chào bạn!<br><br>';
                    $message .= 'Để lấy lại mật khẩu xin bạn vui lòng bấm vào link dưới đây:<br><br>';
                    $message .= 'http://localhost/furniture/admincp/index/resetpassword?id=' . $value['id'] . '&code=' . $code;
                    $mail = new Zend_Mail('UTF-8');
                    $mail->setFrom('thongbao.baotoan@gmail.com', 'Nội thất Bảo Toàn');
                    $mail->addTo($value['email']);
                    $mail->setSubject('Thong bao lay lai mat khau');
                    $mail->setBodyHtml($message);
                    try{
                        $mail->send();
                    }
                    catch(Exception $e){
                        $this->_redirect('admincp/index/login');
                    }
                    $this->_redirect('admincp/index/successforgot');
                }
            }
        }
        
        public function resetpasswordAction()
        {
            $id = $this->_arrParam['id'];
            $code = $this->_arrParam['code'];
            $model = new Admincp_Model_User();
            if((!empty($id)) && (!empty($code))) {
                if($model->checkCode($id, $code) > 0) {
                    $this->_helper->layout->setLayout('resetpassword');
                    $this->view->headTitle('Thay đổi mật khẩu');
            
                    if($this->_request->isPost()) {
                        $strTrim = new Zend_Filter_StringTrim();
                        $password = $strTrim->filter(strip_tags($this->_arrParam['password']));
                        $rePassword = $strTrim->filter(strip_tags($this->_arrParam['rePassword']));
                        $flag = true;
            
                        $validation = new Admincp_Form_ValidateUser();
                        if(!$validation->validPassword($password)) {
                            $this->view->error = 'Mật khẩu có độ dài từ 6-50 kí tự';
                            $flag = false;
                        }
                        if(!$validation->validPassword($rePassword)) {
                            $this->view->error = 'Mật khẩu có độ dài từ 6-50 kí tự';
                            $flag = false;
                        }
                        if($password != $rePassword) {
                            $this->view->error = 'Mật khẩu không trùng khớp';
                            $flag = false;
                        }
            
                        if($flag == true) {
                            $code = time() . mt_rand(5, 99999999);
                            $data = array(
                                'password'=>$this->genPassword($password),
                                'code'=>$code,
                            );
                            $model->updateUser($data, $id);
                            $this->_redirect('admincp/index/success');
                        }
                    }
                }
                else
                {
                    $this->_redirect('');
                }
            }
            else
            {
                $this->_redirect('');
            }
        }
        
        public function successAction()
        {
            $this->_helper->layout->setLayout('success');
            $this->view->headTitle('Thay đổi mật khẩu thành công');
        }
        
        public function successforgotAction()
        {
            $this->_helper->layout->setLayout('success');
            $this->view->headTitle('Xác nhận thông tin thành công');
        }
        
        public function genPassword($password)
        {
            return md5('tivi'.$password);
        }
    }
